<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>多选按钮的使用</title>
</head>
<body>
<div id="change" class="change">
    <form action="" method="get">
        <label for="basketball">
            <input type="checkbox" name="hobbies" id="basketball" value="basketball">篮球
        </label>
        <label for="football">
            <input type="checkbox" name="hobbies" id="football" value="football">足球
        </label>
        <label for="table-tennis">
            <input type="checkbox" name="hobbies" id="table-tennis" value="table-tennis">乒乓
        </label>
        <label for="tennis">
            <input type="checkbox" name="hobbies" id="tennis" value="tennis">网球
        </label>

        <br>
        <!--恢复页面中设置的默认值-->
        <input type="reset" value="reset">
        <!--表单提交到指定的页面-->
        <input type="submit" value="submit">
    </form>

    <h2>你的爱好是: <span>{{ hobbies}}</span></h2>
</div>

<script !src="">
    let hobbies = []
    // step1 获取所有的目标元素
    let elements = document.querySelectorAll("form input[type='checkbox']");

    let element = document.querySelector("h2 span");
    // 调整初始值
    element.innerText = hobbies
    // console.log(elements);

    // step2 遍历判断是否选中
    for (let i = 0; i < elements.length; i++) {
        console.log(elements[i]);

        elements[i].addEventListener(
            "click",
            function (event) {
                if (elements[i].checked) {
                    // console.log(elements[i].value);
                    // hobbies.push(elements[i].value)
                    // console.log(hobbies);
                    // 先判断数组中是否存在该值，如果不存在，添加。如果存在，不变
                    let index = hobbies.indexOf(elements[i].value);
                    if (index === -1) {
                        hobbies.push(elements[i].value)
                        console.log(hobbies);
                        element.innerText = hobbies
                    }

                } else {
                    let index = hobbies.indexOf(elements[i].value);
                    hobbies.splice(index, 1)
                    console.log(hobbies);
                    element.innerText = hobbies
                }
            }
        )
    }

    let element_reset = document.querySelector("form input[type='reset']");
    element_reset.addEventListener(
        "click",
        function () {
            hobbies.splice(0)
            // console.log(hobbies);
            element.innerText = hobbies
        }
    )
</script>
</body>
</html>